#include <iostream>
#include <unistd.h>
#include <string>
#include <pthread.h>
using namespace std;
enum Status{
    OK=0,
    ERROR
};

class ThreadData{
public:
    ThreadData(const string& name,int n,int id)
    :_name(name),
    _n(n),
    _id(id),
    _result(0),
    _status(Status::OK)
    {}
    ~ThreadData(){}
    
public:
    string _name;
    int _n;
    int _id;
    int _result;
    Status _status;
};

void* run(void* arg){
    ThreadData* td = static_cast<ThreadData*>(arg);
    for(int i = 0;i<=td->_n;++i){
        td->_result+=i;
    }
    cout<<"线程: "<<td->_name<<"执行完毕"<<endl;
    pthread_exit(arg);
}

int main()
{
    pthread_t pths[5];
    for(int i = 1;i<=5;++i){
        char* name = new char[64];
        snprintf(name,64,"thread-%d",i);
        ThreadData* threadData = new ThreadData(name,i*100,i);
        pthread_create(&pths[i-1],nullptr,run,threadData);
        sleep(1);
    }
    void* retval = nullptr;
    for(int i = 1;i<=5;++i){
        if(pthread_join(pths[i-1],&retval)!=0){
            perror("线程等待失败！");
            exit(1);
        }
        ThreadData* td = static_cast<ThreadData*>(retval);
        if(td->_status == Status::OK){
            printf("线程%s,计算[1~%d]的结果为：%d\n",td->_name.c_str(),td->_n,td->_result);
        }
        delete td;
    }
    cout<<"所有线程退出完毕"<<endl;
    return 0;
}